package com.example.zyfypt_713zxy.activities;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.ActionMenuItemView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import android.widget.Toast;

import com.example.zyfypt_713zxy.R;
import com.example.zyfypt_713zxy.iface.CollectListener;
import com.example.zyfypt_713zxy.iface.FocusListener;
import com.example.zyfypt_713zxy.model.CollectModel;
import com.example.zyfypt_713zxy.model.FocusModel;
import com.example.zyfypt_713zxy.service.RetrofitService;
import com.github.barteksc.pdfviewer.PDFView;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ViewPDFActivity extends AppCompatActivity {
    private PDFView pdfView;

    private int resid, authorid;//资源id
    Context context;
    private String pdfattach;
    private Boolean flagcollect = false;//收藏标志
    private boolean flagfocus = false;
    private CollectModel collectmodel;//收藏model
    private FocusModel focusModel;
    private SharedPreferences sp;//简单存储
    private String sessionID = "";  //sessionid
    private ActionMenuItemView item, item2;
    //设置Retrofit访问网络的超时时间
    private static final OkHttpClient client =
            new OkHttpClient.Builder().
                    connectTimeout(600, TimeUnit.SECONDS).
                    readTimeout(600, TimeUnit.SECONDS).
                    writeTimeout(600, TimeUnit.SECONDS).build();
    FocusListener listeners = new FocusListener() {
        @SuppressLint("RestrictedApi")
        @Override
        public void onResponse(String msg) {
            if (item2 == null)
                item2 = findViewById(R.id.menufocus);
            switch (msg) {
                case "2":
                    System.out.println("----关注成功");
                    flagfocus = true;
                    item2.setTitle("取消关注");
                    break;
                case "1":
                    System.out.println("----关注失败");
                    break;
                case "4":
                    System.out.println("----取消关注成功");
                    flagfocus = false;
                    item2.setTitle("关注");
                    break;
                case "3":
                    System.out.println("----取消关注失败");
                    break;
                case "5":
                    System.out.println("----已关注");
                    flagfocus = true;
                    item2.setTitle("取消关注");
                    break;
                case "6":
                    System.out.println("----未关注");
                    flagfocus = false;
                    item2.setTitle("关注");
                    break;
                default:
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onFail(String msg) {
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
    };
    CollectListener listener = new CollectListener() {
        @SuppressLint("RestrictedApi")
        @Override
        public void onResponse(String msg) {
            if (item == null)
                item = findViewById(R.id.menucollect);
            switch (msg) {
                case "2":
                    System.out.println("----收藏成功");
                    flagcollect = true;
                    item.setTitle("取消收藏");
                    break;
                case "1":
                    System.out.println("----收藏失败");
                    break;
                case "4":
                    System.out.println("----取消收藏成功");
                    flagcollect = false;
                    item.setTitle("收藏");
                    break;
                case "3":
                    System.out.println("----取消收藏失败");
                    break;
                case "5":
                    System.out.println("----已收藏");
                    flagcollect = true;
                    item.setTitle("取消收藏");
                    break;
                case "6":
                    System.out.println("----未收藏");
                    flagcollect = false;
                    item.setTitle("收藏");
                    break;
                default:
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onFail(String msg) {
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_p_d_f);
        context = ViewPDFActivity.this;
        initViews();
        sp = context.getSharedPreferences("login", MODE_PRIVATE);
        readSP();
        //setLoadingState(true);
        loadPdf();
    }

    private void readSP() {
        sessionID = sp.getString("session", null);

    }

    private void initViews() {
        pdfView = (PDFView) findViewById(R.id.pdfView);
        resid = getIntent().getIntExtra("resid", -1);
        authorid = getIntent().getIntExtra("authorid", -1);
        pdfattach = getIntent().getStringExtra("pdfattach");
    }

    public boolean onCreateOptionsMenu(Menu menu) {//
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menucollect, menu);
        focusModel = new FocusModel();
        collectmodel = new CollectModel();//实例化对象
        collectmodel.exist("tware", resid, sessionID, listener);//判断是否收藏
        focusModel.exist("userfocus", authorid, sessionID, listeners);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menucollect:
                if (flagcollect)//如果已收藏，则调用取消收藏
                {
                    System.out.println("----准备取消收藏");
                    collectmodel.uncollect("tware", resid, sessionID, listener);
                } else//如果未收藏，则调用收藏
                {
                    System.out.println("----准备收藏");
                    collectmodel.collect("tware", resid, sessionID, listener);
                }
                break;
            case R.id.menufocus:
                if (flagfocus) {
                    System.out.println("---准备取消关注");
                    focusModel.unfocus("userfocus", authorid, sessionID, listeners);
                } else {
                    System.out.println("---准备关注");
                    focusModel.focus("userfocus", authorid, sessionID, listeners);
                }
                break;


        }
        return super.onOptionsItemSelected(item);
    }


    private void loadPdf(){

        //显示本地文件（assets目录下的文件）
//        pdfView.fromAsset("fragment.pdf").load();
//        pdfView.fromAsset("Thinking_in_Java_4th_edition.pdf").swipeHorizontal(true).load();

        //显示在线文件（校内网测试文件）
        String baseUrl = "http://amicool.neusoft.edu.cn/Uploads/";
        //String url = "tware/pdfattach/20170524/20170524122736_810326265.pdf";


        //显示在线文件（互联网测试文件）
//        baseUrl = "https://kotlinlang.org/";
//        url = "docs/kotlin-docs.pdf";

        Retrofit retrofit =
                new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .client(client)
                        .build();


        RetrofitService service = retrofit.create(RetrofitService.class);

        final Call<ResponseBody> call = service.getPdf(baseUrl+pdfattach);

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                if (response.isSuccessful()){

                    try {
                        byte[] data = response.body().bytes();
                        //加载PDF
                        pdfView.fromBytes(data).swipeHorizontal(true).load();
                        //隐藏进度
                        // setLoadingState(false);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("--网路错误");
            }
        });
    }
}
